"""棋盘模块"""
from select import select


class Board:
    """棋盘类"""

    def __init__(self):
        self.board_data = [' '] * 9  # 记录每个位置的棋子
        self.moveable_list = list(range(9))  # 剩余可以放入棋子的位置

    def show_board(self, is_show_index=False):
        """显示棋盘
        :param is_show_index:true打印索引;false:默认打印落子

        """
        for i in (0, 3, 6):
            # 每一次循环打印一行
            print('     ｜     ｜     ')
            if is_show_index:
                print('  %d  ｜  %d  ｜  %d  ' % (i, i + 1, i + 2))
            else:
                print('  %s  ｜  %s  ｜  %s  ' % (self.board_data[i], self.board_data[i + 1], self.board_data[i + 2]))
            print('     ｜     ｜     ')
            if i != 6:
                print('-' * 17)

    def move_down(self, index, chess):
        """落子"""
        # 检查下表是否在可落子的列表里
        if index not in self.moveable_list:
            print('%d 不能落子' % index)
            return
        # 落子
        self.board_data[index] = chess

        # 将下标从可落子的列表里移除
        self.moveable_list.remove(index)

    def is_dogfall(self):
        """判断是否平局"""
        # 1.判断是否还有可落子的位置
        return not self.moveable_list

    def is_win(self, chess,ai_index=-1):
        """判断是否胜利
        :param chess 根据落子在获胜数组里是否匹配，若匹配则胜利
        """
        # 准备好所有的获胜方向数组
        check_dirs = [
            [0, 1, 2], [3, 4, 5], [6, 7, 8],
            [0, 3, 6], [1, 4, 7], [2, 5, 8],
            [0, 4, 8], [2, 4, 6]
        ]

        # 把落子列表赋值为临时里变量，为AI做准备
        data = self.board_data.copy()

        #判断是否要模拟落子
        if ai_index>=0:
            data[ai_index] = chess

        # 判断每一个方向，查看是否全都是当前参数的棋子
        for item in check_dirs:
            # 判断当前方向是否都为当前棋子
            if data[item[0]] == chess and data[item[1]] == chess and data[item[2]] == chess:
                return True

        return False

    def reset_board(self):
        """重置棋盘数据"""
        #1.清空剩余的可落子位置
        self.moveable_list.clear()
        #2.重新放置棋盘数据
        for i in range(9):
            self.board_data[i] = ' '
            self.moveable_list.append(i)


if __name__ == '__main__':
    # 1.测试棋盘初始化
    board = Board()
    # print(board.board_data)
    # print(board.moveable_list)

    # 2.测试显示棋盘
    # board.show_board(True)
    # print('')
    # board.board_data[0]='X'
    # board.board_data[4]='O'
    # board.show_board()

    # 测试落子
    # board.move_down(1,'X')
    # print(board.board_data)
    # print(board.moveable_list)
    # board.move_down(8,'O')
    # print(board.board_data)
    # print(board.show_board())

    # 测试平局
    # print(board.is_dogfall())
    # board.moveable_list.clear()
    # print(board.is_dogfall())

    # 测试是否胜利
    # board.move_down(0, 'X')
    # board.move_down(4, 'X')
    # board.move_down(8, 'X')
    # print(board.is_win('O'))
    # board.show_board()

    #测试棋盘重置
    board.reset_board()
    print(board.moveable_list)
    board.show_board()
